//
//  BaseTableVC.m
//  ocCrazy
//
//  Created by mac on 2018/7/3.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "BaseTableVC.h"

#import "BaseTableViewHeaderFooterView.h"
#import <objc/runtime.h>
#import "Tool.h"
#import "BaseTableVC+Tool.h"
#import "AFNetworkReachabilityManager.h"

typedef NS_ENUM(NSInteger, BaseTableVCError) {
    BaseTableVCErrorDelegate = 0,
    BaseTableVCErrorDataSource = 1,
    BaseTableVCErrorTableViewInterface,
};





@interface BaseTableVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSArray <NSString *> *headFootArr;

@property (nonatomic, strong) NSArray *noHeaderArr;
@property (nonatomic, strong) NSArray *noFooterArr;

@end

@implementation BaseTableVC


- (void)viewDidLoad {
    if (!self.tableViewInterface ) [self DebugLog:BaseTableVCErrorTableViewInterface];
    
    if ([self.tableViewInterface respondsToSelector:@selector(classArr)]) self.classStrArr = [self.tableViewInterface classArr];
    
    
    if ([self.tableViewInterface respondsToSelector:@selector(viewClassForSectionFooterHeader)]) self.headFootArr = [self.tableViewInterface viewClassForSectionFooterHeader];
    
    _page = 1;
    
    [super viewDidLoad];
    if (!self.tableView.delegate ) [self DebugLog:BaseTableVCErrorDelegate];
    if (!self.tableView.dataSource) [self DebugLog:BaseTableVCErrorDataSource];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.tableView isGroup];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self.tableView setShowsHorizontalScrollIndicator:NO];
    [self.tableView setShowsVerticalScrollIndicator:NO];
    
}
- (void)needHeadReresh{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf->_page = 1;
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi){
                [self getData:strongSelf->_page];
            }else{
    
                [self.tableView.mj_header endRefreshing];
            }
        }];
        
        
    }];
}
- (void)needFootReresh{
    __weak typeof(self) weakSelf = self;
   self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf->_page++;
       [[AFNetworkReachabilityManager sharedManager] startMonitoring];
       [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
           if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi){
               [self getData:strongSelf->_page];
           }else{
   
               [self.tableView.mj_footer endRefreshing];
           }
       }];
        
    }];
}


- (void)needRefresh{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf->_page = 1;
        
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi){
                [self getData:strongSelf->_page];
            }else{
    
                [self.tableView.mj_header endRefreshing];
            }
        }];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf->_page++;
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi){
                [self getData:strongSelf->_page];
            }else{
    
                [self.tableView.mj_footer endRefreshing];
            }
        }];
    }];
}


- (void)reloadTableView{
    if ([self.tableViewInterface respondsToSelector:@selector(classArr)]){
       self.classStrArr = [self.tableViewInterface classArr];
    }
     if ([self.tableViewInterface respondsToSelector:@selector(viewClassForSectionFooterHeader)]) self.headFootArr = [self.tableViewInterface viewClassForSectionFooterHeader];
    
    if ([self.tableViewInterface respondsToSelector:@selector(noViewHeaderSection)]) self.noHeaderArr = self.tableViewInterface.noViewHeaderSection;
       
    
    [self.tableView reloadData];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self countSection];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self countRow:section];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self getCell:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeight:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([self.tableViewInterface respondsToSelector:@selector(sectionFooterHeight:)]) {
        return [self.tableViewInterface sectionFooterHeight:section];
    }
    if ([self.noFooterArr containsObject:@(section)]) return CGFLOAT_MIN;
    if (self.headFootArr && self.headFootArr.count == 2) {
       Class Footer = NSClassFromString(self.headFootArr[1]);
        if (Footer) {
            return [Footer viewHeight:nil withSection:section];
        }
    }
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([self.tableViewInterface respondsToSelector:@selector(sectionHeaderHeight:)]) {
        return [self.tableViewInterface sectionHeaderHeight:section];
    }
    if ([self.noHeaderArr containsObject:@(section)]) return CGFLOAT_MIN;
    if (self.headFootArr && self.headFootArr.count >= 1) {
        if (self.headFootArr[0] == nil || [self.headFootArr[0] isEqualToString:@""])return CGFLOAT_MIN;
        Class Header = NSClassFromString(self.headFootArr[0]);
        if (Header) {
            return [Header viewHeight:nil withSection:section];
        }
    }
    return CGFLOAT_MIN;
}



-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    BaseTableViewHeaderFooterView *footer = nil;
    if ([self.noFooterArr containsObject:@(section)]) return footer;
    if (self.headFootArr && self.headFootArr.count == 2) {
        Class Footer = NSClassFromString(self.headFootArr[1]);
        if (Footer) {
            id footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headFootArr[1]];
            [footerView setSection:section];
            [footerView setHeaderFooterEvent:self.headerFooterEvent];
            [footerView setModel:[self getHeaderFooterModel:section withType:LCBaseTableVCSectionTypeFooter]];
            footer = footerView;
        }
    }
    return footer;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BaseTableViewHeaderFooterView *header = nil;
    if ([self.noHeaderArr containsObject:@(section)]) return header;
    if ( self.headFootArr && self.headFootArr.count >= 1) {
        if (self.headFootArr[0] == nil || [self.headFootArr[0] isEqualToString:@""])return header;
        Class Header = NSClassFromString(self.headFootArr[0]);
        if (Header) {
            id headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headFootArr[0]];
            [headerView setSection:section];
            
            [headerView setHeaderFooterEvent:self.headerFooterEvent];
            [headerView setModel:[self getHeaderFooterModel:section withType:LCBaseTableVCSectionTypeHeader]];
            header = headerView;
        }
    }
    return header;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.tableViewInterface respondsToSelector:@selector(tableViewSelectAtIndexPath:)]) return [self.tableViewInterface tableViewSelectAtIndexPath:indexPath];
}



-(void)setClassStrArr:(NSArray<NSArray<NSString *> *> *)classStrArr{
    _classStrArr = classStrArr;
    if (_classStrArr != nil) {
        [self.tableView setCellArrForResCell:CellArr(classStrArr)];
    }
}

-(void)setHeadFootArr:(NSArray<NSString *> *)headFootArr{
    _headFootArr = headFootArr;
    if (headFootArr) {
        [self.tableView setHeaderFooterArr:headFootArr];
    }
}

-(NSArray *)noHeaderArr{
    if (!_noHeaderArr) {
        if ([self.tableViewInterface respondsToSelector:@selector(noViewHeaderSection)]) {
            _noHeaderArr = [NSArray arrayWithArray:[self.tableViewInterface noViewHeaderSection]];
        }else{
            _noHeaderArr = [NSArray array];
        }
    }
    return _noHeaderArr;
}

-(NSArray *)noFooterArr{
    if (!_noFooterArr) {
        if ([self.tableViewInterface respondsToSelector:@selector(noViewFooterSection)]) {
            _noFooterArr = [NSArray arrayWithArray:[self.tableViewInterface noViewFooterSection]];
        }else{
            _noFooterArr = [NSArray array];
        }
    }
    return _noFooterArr;
}


-(NSMutableArray *)dataSouece{
    if (!_dataSouece) {
        _dataSouece = [NSMutableArray array];
    }
    return _dataSouece;
}

-(BaseModel<BaseCellModelProtocol> *)dataSourceModel{
    if (!_dataSourceModel) {
        _dataSourceModel = [BaseModel new];
        
    }
    return _dataSourceModel;
}


- (BaseModel *)getHeaderFooterModel:(NSInteger )section withType:(LCBaseTableVCSectionType)type{
    BaseModel *model;
    if ([self.tableViewInterface respondsToSelector:@selector(modelForHeaderFooter:withType:)]) {
        model = [self.tableViewInterface modelForHeaderFooter:section withType:type];
    }
    return model;
}

- (void)detailModelwithArr:(NSArray <__kindof BaseModel *> *)arr withCallBack:(void(^)(void))callBack{
    if (self.page == 1) {
        [self.dataSouece removeAllObjects];
    }
    for (__kindof BaseModel *model in arr) {
        [self.dataSouece addObject:model];
    }
    if (callBack) {
        callBack();
    }
    [self.tableView cc_endReFresh:arr];
}

- (void)DebugLog:(BaseTableVCError)error{
#ifdef DEBUG
    switch (error) {
        case BaseTableVCErrorDelegate:
            NSLog(@"\n ⚠️⚠️⚠️ \n %@ 这个类的tableView 没有设置delegate",[self class]);
            break;
        case BaseTableVCErrorDataSource:
            NSLog(@"\n ⚠️⚠️⚠️ \n %@ 这个类的tableView 没有设置dataSource",[self class]);
            break;
        case BaseTableVCErrorTableViewInterface:
            NSLog(@"\n ⚠️⚠️⚠️ \n %@ 这个类的tableViewInterface 没有设置\n tableViewInterface  需要设置在[super viewDidLoad]前",[self class]);
            break;
        default:
            break;
    }
#endif
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
